#! /usr/bin/env python
#
import sys
import os

import ctypes

from fitsio import cfitsio, pyfitsio

def main():
    '''
    Create a FITS primary array containing a 2-D image
    '''

    filename = 'atestfil.fit'

    # Image is 300 by 200 pixels
    naxes = (300, 200)
    npix = naxes[0] * naxes[1]

    # Allocate memory for the whole image and fill up with ramp function
    array = (ctypes.c_short * npix)()
    for j in range(naxes[1]):
        for i in range(naxes[0]):
            array[j * naxes[0] + i] = i + j

    # Get a pythonic object to represent the file. Overwrite if file 
    # already exists
    ff = pyfitsio.open(filename, mode='w', clobber=True)
    ff.create_image(naxes, cfitsio.USHORT_IMG)

    # Write the array using direct call the CFITSIO function
    status = ctypes.c_int(0)
    fpixel = ctypes.c_longlong(1)
    nelements = ctypes.c_longlong(npix)
    cfitsio.fits_write_img(ff.fptr, cfitsio.TUSHORT, fpixel, nelements, array,
                           ctypes.byref(status))

    pyfitsio.check_error(status)

    # Write optional keyword (write as python int rather than long)
    exposure = 1500
    ff.write_key('EXPOSURE', exposure, 'Total Exposure Time')

    
    # Close the file
    ff.close()
    

if __name__ == '__main__':
    main()
